#include "Scanner.h"
#include "Parser.h"

#include <fstream>
#include <iostream>

using namespace std;

int main(int argv, char* args[]) {

  if(argv != 3) {
    cout << "Usage: ./compiler <grammar_file> <input_file>" << endl;
    return -1;
  }

  //Try to parse sample grammar
  Scanner *grammar_reader = new Scanner();
  int result = grammar_reader->readFile(args[1]);

  if(result != 1) {
    printf("Can't parse Grammar!\n Result: %d\n", result);
    return -1;
  }

  //If File is able to be read, then read grammar + print out details
  grammar_reader->readGrammar();
  grammar_reader->printVectors();

  //File Reader
  Scanner *intput_reader = new Scanner();
  result = intput_reader->readFile(args[2]);
  
  if(result != 1) { //file exists
    printf("Can't parse Input File!\n Result: %d\n", result);
    return -1;
  }

  //Part 1. Read Grammar and Input file and then output to translation.txt
  int semicolon_flag = 0;
  string curr_line;
  string curr_token = intput_reader->nextLine() ;

  ofstream outputfile("translation.txt");
  

  //Parses input file -> Also Fix ; placement
  while(curr_token.compare("") != 0) {
    //Search for ;
    int last_char = curr_token.length()-1;
    if(curr_token.length() > 1 && curr_token[last_char] == ';' && curr_token[last_char-1] != ' ') {
      semicolon_flag = 1;
      string withoutsemi = curr_token.substr(0, curr_token.length()-1);
      curr_token = withoutsemi.append(" ;");
    }

    istringstream *ss = new istringstream(curr_token);
    
    string withoutsemi  = "";

    do {
      string current;
      if(semicolon_flag == 0)
        *ss >> current;
      else {
        current = ";";
        semicolon_flag = 0;
      }

      string translation = "";

      if(current[current.length()-1] == ';' && current.length() > 1) {
        semicolon_flag = 1;
        string withoutsemi = current.substr(0, current.length()-1);
        translation = grammar_reader->matchSymbol(withoutsemi);
      }
      else {
        translation = grammar_reader->matchSymbol(current);
      }

      curr_line.append(translation);
      curr_line.append(" ");
    } while(ss->good());

    outputfile << curr_line << endl;
    curr_line = "";

    curr_token = intput_reader->nextLine();
  }

  cout << endl << endl;

  return 0;
}
